# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
from resources_base.module_base.basetools import md5
# ========= 导入数据的类 ============
from userweb.models import Account
# ==========导入其他模块 =============
from django_redis import get_redis_connection
from django.core.mail import send_mail


def index(request):
    """返回页面"""
    return render(request, 'user/resetpass.html')


def get_account_info(request):
    """获取员工信息"""
    # 接收传递的值
    input_str = request.POST.get('input_str')
    # 通过值获取对象
    account_obj = Account.objects.filter(Q(mobile=input_str) | Q(email=input_str) | Q(loginid=input_str)).first()
    # 判断是否存在
    if not account_obj:
        return JsonResponse({'status': False, 'error': "输入的账号不存在!"})
    # 返回
    return JsonResponse(
        {'status': True,
         'data': {'loginid': account_obj.loginid, 'name': account_obj.name, 'email': account_obj.email}})


def send_email(request):
    """发送邮件"""
    # 获取要发送的邮箱
    email = request.POST.get('email')
    # 定义一个集合，存储收件人
    send_list = []
    send_list.append(email)
    # 准备邮件的元素
    code = random.randint(10000, 99999)
    email_title = "找回登陆密码的邮件"
    email_body = "当前的验证码：" + str(code) + "\n 【验证码有效期15分钟，请尽快完成密码的修改】"
    # 开始发送邮件
    try:
        result = send_mail(email_title, email_body, '651205558@qq.com', send_list)
        # 判断
        if result == 1:
            # 1. 把验证码写入redis -- 15分钟有效
            redis_obj = get_redis_connection()
            redis_obj.set(email, code, 900)
            # 2. 返回
            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'error': '邮件发送失败，请检查网络！'})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '邮件发送出现未知的异常，具体原因:' + str(e)})


def check_email_code(request):
    """校验验证码"""
    # 接收前台传递的数据
    email = request.POST.get('email')
    code = request.POST.get('code')
    # 在redis中获取
    redis_obj = get_redis_connection()
    # 获取
    redis_code = redis_obj.get(email)
    # 判断
    if not redis_code:
        return JsonResponse({'status': False, 'error': "验证码已过期，请重新获取验证码！"})

    # 判断是否相等
    if redis_code.decode('utf-8') != code:
        return JsonResponse({'status': False, 'error': "验证码错误！"})

    # 返回
    return JsonResponse({'status': True})


def change_pwd(request):
    """修改密码"""
    # 获取传递的值
    loginid = request.POST.get('accountid')
    new_pass = request.POST.get('new_pass')
    # 获取对象
    account_obj = Account.objects.filter(loginid= loginid).first()
    # 修改
    try:
        account_obj.loginpwd = md5(new_pass)
        # 保存
        account_obj.save()
        # 返回
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '修改密码出现未知的异常，具体原因:' + str(e)})